package com.atbeijing.D05;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Comparator;

/**
 * 每个小时中的实时热门(TopN)商品
 * 转换pojo
 * 过滤出pv数据
 * 设置水位线
 * 开窗1h,求出每种商品的点击量
 * 根据窗口开始或结束时间戳分流,将数据存到状态变量,
 * 将状态变量存到list,排序取前N
 *
 */
public class Example9 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .readTextFile("C:\\Users\\WangJinGen\\IdeaProjects\\flink\\data\\UserBehavior.csv")
                .map(new MapFunction<String, UserBehavior>() {
                    @Override
                    public UserBehavior map(String value) throws Exception {
                        String[] s = value.split(",");
                        return new UserBehavior(s[0],s[1],s[2],s[3],Long.parseLong(s[4])*1000L);
                    }
                })
                //只要商品点击数据
                .filter(r -> r.behaviorType.equals("pv"))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                //无延迟
                                .<UserBehavior>forMonotonousTimestamps()
                                //水位线字段
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>(){
                                    @Override
                                    public long extractTimestamp(UserBehavior element, long recordTimestamp) {
                                        return element.timestamp;
                                    }
                                })
                )
                //根据商品id分流
                .keyBy(r -> r.itemId)
                .window(TumblingEventTimeWindows.of(Time.hours(1)))
                //聚合求出每1小时各个商品的点击总和
                .aggregate(new Agg8(),new ResultWindow8())
                //根据窗口分流,每条流表示1小时各个商品的点击总和
                .keyBy(r ->r.windowEnd)
                .process(new TopN(3))
                .print();

        env.execute();

    }

    public static class TopN extends KeyedProcessFunction<Long,ItemViewCount,String>{
        private int N;

        public TopN(int n) {
            N = n;
        }

        //状态变量:接收一小时商品点击情况
        private ListState<ItemViewCount> itemState;

        @Override
        public void open(Configuration parameters) throws Exception {
            super.open(parameters);
            itemState=getRuntimeContext().getListState(new ListStateDescriptor<ItemViewCount>("item-state", Types.POJO(ItemViewCount.class)));
        }

        @Override
        public void processElement(ItemViewCount value, Context ctx, Collector<String> out) throws Exception {
            itemState.add(value);
            //只有事件到达process才会根据UserBehavior.timestamp设置水位线,这里延迟200ms保证一个窗口的数据都到了
            ctx.timerService().registerEventTimeTimer(value.windowEnd+200L);
        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
            super.onTimer(timestamp, ctx, out);
            //导入list并排序,降序
            ArrayList<ItemViewCount> itemViewCounts = new ArrayList<>();
            for (ItemViewCount itemViewCount : itemState.get()) {
                itemViewCounts.add(itemViewCount);
            }
            itemViewCounts.sort(new Comparator<ItemViewCount>() {
                @Override
                public int compare(ItemViewCount o1, ItemViewCount o2) {
                    return o2.count.intValue()-o1.count.intValue();
                }
            });
            //结果
            StringBuilder result = new StringBuilder();
            result
                    .append("=====================================\n");
            for (int i = 0; i < N; i++) {
                ItemViewCount itemViewCount = itemViewCounts.get(i);
                result
                        .append("窗口结束时间是：" + new Timestamp(timestamp - 200L))
                        .append("第" + (i + 1) + "名的商品id是：" + itemViewCount.itemId)
                        .append("浏览次数是：" + itemViewCount.count + "\n");
            }
            result
                    .append("=====================================\n");

            out.collect(result.toString());
        }
    }

    //增量聚合维护个累加器,窗口闭合后
    public static class Agg8 implements AggregateFunction<UserBehavior,Long,Long>{
        @Override
        public Long createAccumulator() {
            return 0L;
        }

        @Override
        public Long add(UserBehavior value, Long accumulator) {
            return accumulator+1L;
        }

        @Override
        public Long getResult(Long accumulator) {
            return accumulator;
        }

        @Override
        public Long merge(Long a, Long b) {
            return null;
        }
    }

    public static class ResultWindow8 extends ProcessWindowFunction<Long,ItemViewCount,String, TimeWindow>{
        @Override
        public void process(String s, Context ctx, Iterable<Long> elements, Collector<ItemViewCount> out) throws Exception {
            out.collect(new ItemViewCount(s,elements.iterator().next(),ctx.window().getStart(),ctx.window().getEnd()));
        }
    }

    public static class ItemViewCount {
        public String itemId;
        public Long count;
        public Long windowStart;
        public Long windowEnd;

        public ItemViewCount() {
        }

        public ItemViewCount(String itemId, Long count, Long windowStart, Long windowEnd) {
            this.itemId = itemId;
            this.count = count;
            this.windowStart = windowStart;
            this.windowEnd = windowEnd;
        }

        @Override
        public String toString() {
            return "ItemViewCount{" +
                    "itemId='" + itemId + '\'' +
                    ", count=" + count +
                    ", windowStart=" + new Timestamp(windowStart) +
                    ", windowEnd=" + new Timestamp(windowEnd) +
                    '}';
        }
    }

    public static class UserBehavior {
        public String userId;
        public String itemId;
        public String categoryId;
        public String behaviorType;
        public Long timestamp;

        public UserBehavior() {
        }

        public UserBehavior(String userId, String itemId, String categoryId, String behaviorType, Long timestamp) {
            this.userId = userId;
            this.itemId = itemId;
            this.categoryId = categoryId;
            this.behaviorType = behaviorType;
            this.timestamp = timestamp;
        }

        @Override
        public String toString() {
            return "UserBehavior{" +
                    "userId='" + userId + '\'' +
                    ", itemId='" + itemId + '\'' +
                    ", categoryId='" + categoryId + '\'' +
                    ", behaviorType='" + behaviorType + '\'' +
                    ", timestamp=" + new Timestamp(timestamp) +
                    '}';
        }
    }
}
